package com.dag.account.utils;

import com.dag.account.constants.FundFlowTypeEnum;
import com.dag.account.dao.entity.TradeRecord;
import com.dag.common.exception.BusinessRuntimeException;
import com.dag.seqno.Sequence;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 交易工具类
 */
@Component
public class TradeUtils {

    private static Sequence sequence;

    @Autowired
    public void setSequence(Sequence sequence){
        TradeUtils.sequence = sequence;
    }

    /**
     * 获取交易记录序列号
     */
    public static String buildSeqNo(){
        return sequence.getFixedLengthSeqNo("acc_trade_record", 8, "T");
    }


    /**
     * 生成交易对方
     */
    public static TradeRecord copyAndReverse(TradeRecord tradeRecord){
        // 交易对方
        TradeRecord otherTradeRecord = new TradeRecord();
        // 复制所有属性
        BeanUtils.copyProperties(tradeRecord, otherTradeRecord);

        // 转换身份
        otherTradeRecord.setSerialNo(TradeUtils.buildSeqNo());
        otherTradeRecord.setMemberId(tradeRecord.getOtherMemberId());
        otherTradeRecord.setMemberName(tradeRecord.getOtherMemberName());
        otherTradeRecord.setAccountId(tradeRecord.getOtherAccountId());
        otherTradeRecord.setOtherMemberId(tradeRecord.getMemberId());
        otherTradeRecord.setOtherMemberName(tradeRecord.getMemberName());
        otherTradeRecord.setOtherAccountId(tradeRecord.getAccountId());
        BigDecimal amount = otherTradeRecord.getAmount();
        otherTradeRecord.setAmount(amount.multiply(BigDecimal.valueOf(-1)));
        Integer fundFlowType = tradeRecord.getFundFlowType();
        if(fundFlowType == FundFlowTypeEnum.INCOME.getIndex()){
            otherTradeRecord.setFundFlowType(FundFlowTypeEnum.PAY.getIndex());
        }else if(fundFlowType == FundFlowTypeEnum.PAY.getIndex()){
            otherTradeRecord.setFundFlowType(FundFlowTypeEnum.INCOME.getIndex());
        }else{
            throw new BusinessRuntimeException("错误的收支类型");
        }
        return otherTradeRecord;
    }

}
